package server.doc.xml;

//import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import org.dom4j.*;

//import common.models.ChatHistoryItem;
import common.models.MvcModel;
import server.config.Public;

public class XMLChatHistory extends XMLDoc {
	
	int uid;

	public XMLChatHistory(int uid) {
		super("data/history/" + Integer.toString(uid) + ".xml");
	}

	synchronized public void addItem(int from, int to, String content) {
		Document xml = getXML();
		Element root = xml.getRootElement();
		int fuid;
		if (from == uid)
			fuid = to;
		else
			fuid = from;
		Node node = root.selectSingleNode("/history/friend[@userID='" + Integer.toString(fuid) + "']");
		Element elem = null;
		if (node instanceof Element) {
			elem = ((Element) node).addElement("item");
		} else {
			Element friend = root.addElement("friend");
			friend.addAttribute("userID", Integer.toString(fuid));
			elem = friend.addElement("item");
		}
		elem.addElement("time").setText(Public.dateFormat.format((new Date())));
		elem.addElement("from").setText(Integer.toString(from));
		elem.addElement("to").setText(Integer.toString(to));
		elem.addElement("content").setText(content);
		writeFile(xml);
	}
	
	synchronized public Vector<Vector<String>> getHistory(int fuid) {
		Document xml = getXML();
		Element root = xml.getRootElement();
		Node node = root.selectSingleNode("/history/friend[@userID='" + Integer.toString(fuid) + "']");
		Vector<Vector<String>> history = new Vector<Vector<String>>();
		if (node instanceof Element) {
			Element elem = (Element) node;
			List list = elem.selectNodes("item");
			for (int i = 0; i < list.size(); ++i) {
				if (list.get(i) instanceof Element) {
					Element e = (Element) list.get(i);
					Vector<String> v = new Vector<String>();
					v.add(e.element("time").getText());
					v.add(e.element("from").getText());
					v.add(e.element("to").getText());
					v.add(e.element("content").getText());
					history.add(v);
//					try {
//						ChatHistoryItem item = new ChatHistoryItem(Public.dateFormat.parse(e.element("time").getText()),
//							Integer.parseInt(e.element("from").getText()),
//							Integer.parseInt(e.element("to").getText()), e.element("content").getText());
//						history.add(item);
//					} catch (ParseException exception) {
						// do nothing
//					}
				}
			}
		}
		return history;
	}
	
	//@Override
	public void addEntry(MvcModel entry) {
		// TODO Auto-generated method stub
		
	}

	//@Override
	public void deleteEntry(MvcModel entry) {
		// TODO Auto-generated method stub
		
	}

	//@Override
	public void updateEntry(MvcModel entry) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Document initXML() {
		// TODO Auto-generated method stub
		Document xml = DocumentHelper.createDocument();
		xml.addElement("history");
		return xml;
	}
}
